package com.fmjr.web.ftlvariables;

import com.fmjr.common.util.SpringUtil;
import com.fmjr.sys.sysDic.bean.SysDic;
import com.fmjr.sys.sysDic.service.ISysDicService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SysDicWriterDirective implements TemplateDirectiveModel {

	private String dicType;// 瀛楀吀绫诲瀷

	private String dicValue;// 瀛楀吀鍊�

	private ISysDicService sysDicService = (ISysDicService) SpringUtil.getBean("sysDicService");

	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String result = "";
		settingsValues(params);
		if (StringUtils.isEmpty(this.dicValue)) {
			result = "";
		} else {
			SysDic sysDicBean = this.getDict();
			if (sysDicBean != null) {
				result = sysDicBean.getDicCode();
			}
		}

		env.getOut().write(result);
	}

	/**
	 * @Description: setting values
	 * @date 2017骞�4鏈�5鏃� 涓嬪崍3:26:05
	 * @version V1.0
	 * @param params
	 */
	private void settingsValues(@SuppressWarnings("rawtypes") Map params) {
		if (params.get("dicType") != null) {
			this.dicType = params.get("dicType").toString();
		}
		if (params.get("dicValue") != null) {
			this.dicValue = params.get("dicValue").toString();
		}
	}

	public SysDic getDict() {
		if (this.dicType == null || this.dicValue == null) {
			return null;
		}
		SysDic sysDic = null;
		List<SysDic> list = getDicts();
		if (list != null && list.size() > 0) {

			for (int i = 0; i < list.size(); i++) {
				sysDic = list.get(i);
				if (sysDic != null && sysDic.getDicType().equals(this.dicType) && sysDic.getDicValue().equals(this.dicValue)) {
					break;
				}
			}
		}

		return sysDic;
	}

	public List<SysDic> getDicts() {
		List<SysDic> SysDicList = new ArrayList<SysDic>();
		if (this.dicType == null) {
			return null;
		}
		List<SysDic> list = sysDicService.selectSysDicAll();
		if (list != null && list.size() > 0) {
			SysDic sysDic = null;
			for (int i = 0; i < list.size(); i++) {
				sysDic = list.get(i);
				if (sysDic != null && sysDic.getDicType().equals(this.dicType)) {
					SysDicList.add(sysDic);
				}
			}
		}

		return SysDicList;
	}

}